<?php
// +----------------------------------------------------------------------
// | 生成数据缓存类后台 (for thinkphp)
// +----------------------------------------------------------------------
// | @link ( http://www.yurnero.net )
// +----------------------------------------------------------------------
// | @copyright
// +----------------------------------------------------------------------
// | @licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | @author Haijun Wu <nicholasinlove@126.com>
// +----------------------------------------------------------------------
// | $Id: StaticCaches.class.php 114 2011-05-11 03:49:28Z nicholasinlove1986@gmail.com $
// +----------------------------------------------------------------------

/**
 +------------------------------------------------------------------------
 * 使用实例
 +------------------------------------------------------------------------
 * import("@.ORG.StaticCaches");			     导入库
 * $cache = new StaticCaches();                  实例化
 * $cache->cacheInit();		                     初始化缓存
 * $cache->cacheLoad();		                     刷新缓存(支持数组或者字符串)		
 +------------------------------------------------------------------------
 */
 
 
class StaticCaches extends Think {

	/**
	 * 内部数据对象
	 */
	//private $db;
	
	/**
	 * 静态缓存绝对路径
	 */
	private $path;
	
	/**
	 * 构造函数
	 */
	public function __construct() {
		//$this->db = &$db;
		$this->path = ROOT_PATH . STATIC_CACHES_DIR;
		//$this->cacheInit();
	}


	/**
	 * 初始化缓存
	 */
	public function cacheInit() {
		$cache_list = array('calendar', 'category', 'cat_option', 'category_isshow', 'comment', 'links', 'posts', 'system_config','tag','statistics');
		foreach ( $cache_list as $cache ) {
			$cache_name = $this->path . $cache . '_static.php';
			if ( !file_exists( $cache_name ) ) {
				$this->cacheLoad( $cache );
			}
		}
	}
	
	/**
	 * 刷新缓存
	 *
     * @access  public
     *
     * @param   string/array   $method  支持数组或者字符串,全部则留空
	 * 
     * @return void
     */
	public function cacheLoad($method = NULL){
		// 更新单个缓存
		if (is_string($method)) {
			if (method_exists($this, 'sc_' . $method)) {
				call_user_func(array($this, 'sc_' . $method));
			}
			return;
		}
		// 更新多个缓存
		if (is_array($method)) {
			foreach ($method as $name) {
				if (method_exists($this, 'sc_' . $name)) {
					call_user_func(array($this, 'sc_' . $name));
				}
			}
			return;
		}
		// 更新全部缓存
		if ($method == NULL) {
			$method = get_class_methods($this);
			foreach ($method as $method) {
				if (preg_match('/^sc_/', $method)) {
					call_user_func(array($this, $method));
				}
			}
		}
	}
	
	/**
	 * 系统配置
	 */
	private function sc_system_config() {
		get_config();
	}
	 
	/**
	 * 日历缓存
	 */
	private function sc_calendar() {
		$cal   = $this->path.'calendar_static.php';
		import("@.ORG.Calendar");
		$y = Calendar::local_date('Y');
		$m = Calendar::local_date('m');	
		$date = new Calendar($y,$m);
		$start_time = local_mktime(0,0,0,$m,1,$y);
		$end_time   = local_mktime(0,0,0,$date->nextMonth,1,$date->nextYear);
		$num  = get_posts_from_date($start_time,$end_time);
		$html = $date->outPut($num);	
		if($fp = @fopen($cal, 'wb')) {
			$cachedata = "\$html = unserialize('".addcslashes(serialize($html), '\\\'')."');";
			@fwrite($fp, "<?php\n//nblog cache file\n//Created on " . date('Y-m-d H:i:s',time()) . "\n\nif (!defined('IN_BLOG')) exit('Hacking attempt');\n\n\$expiration='".(time() + 600)."';\r\n".$cachedata."\r\n?>");
			@fclose($fp);
			@chmod($cal, 0777);
		}
	}
	
	/**
	 * 日志分类
	 */
	private function sc_category() {
		$cat  = D('Category');
		$data = $cat->getCatArray();
		$this->cacheFile('category_static',$data ,$this->path); 
	}
	
	/**
	 * 过滤和排序所有日志分类，返回一个带有缩进级别的数组
	 */
	private function sc_cat_option() {
		$cat  = D('Category');
		if (!file_exists($this->path.'category_static.php')) {
			$this->sc_category();
		}
		$data = $this->cacheFile('category_static','',$this->path);
		$data = $cat->getCatOptions($data,$cat_id);
		$this->cacheFile('cat_option_static',$data ,$this->path); 
	}
	
	/**
	 * 隐藏不可显示的分类,经过过滤和排序处理,带有缩进级别的数组
	 */
	private function sc_category_isshow() {
		$cat  = D('Category');
		$data = $cat->getCatList(0,0,0,false,false);
		foreach ($data as $key =>$v) {
			foreach ($v as $k=>$c){
				if($k!='category_id'&&$k!='category_url'&&$k!='category_title'&&$k!='posts_num'&&$k!='level') {
					unset($data[$key][$k]);
				}
			}
		}
		$this->cacheFile('category_isshow_static',$data ,$this->path); 
	}
	
	/**
	 * 友情链接
	 */
	private function sc_links() {
		$links = M('Links');
		$map = array();
		$map['link_status'] = 1; 
		$map['link_visible'] = 1;
		$data = $links->field('link_url,link_name,link_description')->where($map)->order('link_sort asc')->limit(C('links_num'))->findAll();
		$this->cacheFile('links_static',$data ,$this->path); 
	}
	
	/**
	 * 最新评论
	 */
	private function sc_comment() {
		$com = M('Comment');
		$map = array();
		$map[C('DB_PREFIX').'comment.comment_status'] = 1; 
		$map[C('DB_PREFIX').'comment.comment_visible'] = 1;
		$map[C('DB_PREFIX').'comment.comment_type'] = array('neq',2);
		$map[C('DB_PREFIX').'posts.posts_status'] = 1;
		if (C('remark')) {
			$map[C('DB_PREFIX').'comment.comment_remark'] = 1;
		}
		$data = $com->where($map)->field(C('DB_PREFIX').'comment.comment_id,'.C('DB_PREFIX').'comment.posts_id,'.C('DB_PREFIX').'posts.posts_title,'.C('DB_PREFIX').'posts.posts_url,'.C('DB_PREFIX').'comment.comment_content,'.C('DB_PREFIX').'comment.comment_author,'.C('DB_PREFIX').'comment.comment_email,'.C('DB_PREFIX').'comment.comment_url')->join(C('DB_PREFIX').'posts ON '.C('DB_PREFIX').'posts.posts_id = '.C('DB_PREFIX').'comment.posts_id')->order('comment_id desc')->limit(C('recent_comments_num'))->findAll();
		foreach ($data as $k=>$v) {
			//$data[$k]['comment_short_content'] = msubstr(htmlspecialchars(addslashes($v['comment_content'])),0,C('recent_comments_limit'));
			$comment_excerpt = preg_replace('/(\r\n)|(\n)/', '', $v['comment_content']); // 消灭换行符
			$comment_excerpt = rc_remove_blockquotes($comment_excerpt); // 消灭所有 blockquote 内容
			$comment_excerpt = preg_replace('/\<(.+?)\>/', '', $comment_excerpt); // 消灭所有标签
			$data[$k]['comment_short_content'] = msubstr($comment_excerpt, 0, C('recent_comments_limit'));
			$data[$k]['comment_ellipsis']  = (strpos($data[$k]['comment_short_content'],"...")) ? 1 : 0 ;
			$data[$k]['comment_email'] = get_gravatar($data[$k]['comment_email'], $s = 80, $d = C('avatar_default'), $r = C('avatar_rating'));
		}
		$this->cacheFile('comment_static',$data ,$this->path);
	}
	
	/**
	 * 日志归档 默认日期对应日志数
	 */
	private function sc_posts() {
		$posts = M('Posts');
		$map = array();
		$map['posts_status'] = 1; 
		$map['posts_draft'] = 1;
		$map['posts_type'] = 1;
		$data = $posts->where($map)->field('posts_date, count(posts_id) as num')->order('posts_date desc')->group('posts_date')->select();
		$newarr = array();
		foreach ($data as $key => $v) {
				$newarr[$v['posts_date']] = $v['num'];	
		}
		$this->cacheFile('posts_static',$newarr ,$this->path);
	}
	
	/**
	 * 标签
	 */
	private function sc_tag() {
		$tag  = D('Tag');
		$data = $tag->getTagArray();
		foreach ($data as $key =>$v) {
			foreach ($v as $k=>$c){
				if($k=='tag_addtime') {
					unset($data[$key][$k]);
				}
			}
		}
		$this->cacheFile('tag_static',$data ,$this->path);
	}
	
	/**
	 * 统计信息
	 */
	private function sc_statistics() {
		$posts = M('Posts');
		$com   = M('Comment');
		$cat   = M('Category');
		$tag   = M('Tag');
		$tb    = M('Trackback');
		$link  = M('Links');
		//日志
		$posts_map = array();
		$posts_map['posts_status'] = 1; 
		$posts_map['posts_draft'] = 1;
		$posts_map['posts_type'] = 1;
		$posts_num = $posts->where($posts_map)->count();
		//评论
		$comment_sql = '';
		$comment_sql .= ' comment_status = 1 and comment_visible = 1 and comment_type <> 2 ';
		if (C('remark')) {
			$comment_sql .=  ' and comment_remark = 1 ';
		}
		$comment_num = $com->where($comment_sql)->count();
		//留言
		$guestbook_map = array();
		//$guestbook_map['comment_status'] = 1; 
		$guestbook_map['comment_visible'] = 1;
		$guestbook_map['comment_type'] = 2;
		/*if (C('remark')) {
			$comment_map['comment_remark'] = 1;
		}*/
		$guestbook_num = $com->where($guestbook_map)->count();
		//分类
		$category_num = $cat->where('category_isshow = 1')->count();
		//标签
		$tag_num = $tag->count();
		//附件
		$real_list = array();
		$folder = opendir(ROOT_PATH . UPLOAD_DIR);
		while ($file = readdir($folder)) {
			if ((strpos($file,'.doc') || strpos($file,'.pdf') || strpos($file,'.rar') || strpos($file,'.zip'))!== false) {
				$real_list[] = $file;
			}
		}
		$attachment_num = count($real_list);
		//引用通告
		$tb_map = array();
		$tb_map['tb_visible'] = 1;
		$trackback_num = $tb->where($tb_map)->count();
		//访问量
		$today_num = C('today_pv');
		$total_num = C('total_pv');
		$statistics_addtime = gmtime();
		//友情链接
		$link_map = array();
		$link_map['link_status'] = 1; 
		$link_map['link_visible'] = 1;
		$link_num = $link->where($link_map)->count();
		 
		$data = array(
			'posts_num' => !empty($posts_num) ? intval($posts_num) : 0,
			'comment_num' => !empty($comment_num) ? intval($comment_num) : 0,
			'guestbook_num' => !empty($guestbook_num) ? intval($guestbook_num) : 0,
			'category_num' => !empty($category_num) ? intval($category_num) : 0,
			'tag_num' => !empty($tag_num) ? intval($tag_num) : 0,
			'attachment_num' => !empty($attachment_num) ? intval($attachment_num) : 0,
			'trackback_num' => !empty($trackback_num) ? intval($trackback_num) : 0,
			'link_num' => !empty($link_num) ? intval($link_num) : 0,
			'today_num' => !empty($today_num) ? intval($today_num) : 0,
			'total_num' => !empty($total_num) ? intval($total_num) : 0,
			'statistics_addtime' => $statistics_addtime,
		);
		$this->cacheFile('statistics_static',$data ,$this->path);
	}
	
	/**
	 * 快速文件数据读取和保存 针对简单类型数据 字符串、数组
	 */
	public function cacheFile($name,$value='',$path=DATA_PATH) {
		static $_cache = array();
		$filename   =   $path.$name.'.php';
		if('' !== $value) {
			if(is_null($value)) {
				// 删除缓存
				return unlink($filename);
			}else{
				// 缓存数据
				$dir   =  dirname($filename);
				// 目录不存在则创建
				if(!is_dir($dir))  mkdir($dir);
				return file_put_contents($filename,"<?php\n//nblog cache file\n//Created on " . date('Y-m-d H:i:s',time()) . "\n\nif (!defined('IN_BLOG')) exit('Hacking attempt');\n\n\$data = ".var_export($value,true)."\n?>");
			}
		}
		if(isset($_cache[$name])) return $_cache[$name];
		// 获取缓存数据
		if(is_file($filename)) {
			include ($filename);
			$_cache[$name]   =   $data;
		}else{
			$data  =   false;
		}
		return $data;
	}

}

?>